import { createApp } from "vue";
import App from "./App.vue";
import { createWebHashHistory, createRouter } from "vue-router";
import ElementPlus from "element-plus";
import "element-plus/dist/index.css";
import User from "./user/index.vue";
import Swiper from "./swiper/index.vue";
import Login from "./user/login.vue";
import Layout from "./layout/index.vue";
import axios from "axios";

const routes = [
	{
		path: "/",
		name: "layout",
		component: Layout,
		children: [
			{
				path: "/user",
				name: "user",
				component: User,
			},
			{ path: "/swiper", name: "swiper", component: Swiper },
		],
	},
	{ path: "/login", name: "login", component: Login },
];

const router = createRouter({
	history: createWebHashHistory(),
	routes,
});

router.beforeEach(async (to, from, next) => {
	const token = localStorage.getItem("token");
	if (to.name !== "login" && !token) {
		next({ name: "login" });
	} else {
		next();
	}
});

const instance = axios.create({
	baseURL: "http://localhost:9000",
});

instance.defaults.headers.post["Content-Type"] = "application/json";
instance.defaults.headers.common["authorization"] = `${localStorage.getItem(
	"token"
)}`;

const app = createApp(App);
app.config.globalProperties.$api = instance;

app.use(router).use(ElementPlus).mount("#app");
